<?php

namespace App\Http\Middleware;

use App\Common\Menu;
use App\Model\Facades\AdminMenus;
use App\Model\Facades\Users;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

class AdminMeun
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */

    private $menus = null;

    public function handle($request, Closure $next, $guard = null)
    {
        $rols = Users::create()->role;
//        $this->test();
        $boolPower = $this->power();

        if (!$boolPower)
            return redirect('/home');

        if ($rols->id != 1) {

            $pms = $this->menus->where('is_show', 1);
            $treeview = Menu::create()->toTree($pms->toArray());

        } else {
            $treeview = AdminMenus::create()->getToTree()->where('is_show', 1);
        }

        $expiresAt = Carbon::now()->addMinute(60);
        #Cache::put('menus', $this->menus, $expiresAt);
        view()->share('treeview', $treeview);

        return $next($request);
    }

    protected function power()
    {

        $rols = Auth::user()->getroles->first();

        if ($rols->id == 1)
            return true;

        $routeAlias = Route::currentRouteName();
        $menus = AdminMenus::create()->getInfoForAlias($routeAlias);

        #Cache::pull('menus');


        $this->menus = Cache::get('menus') ?: [];

        if (empty($this->menus)) {
            $this->menus = $rols->id != 2 ? $rols->getPermissions : Auth::user()->getPermissions;
        }

        return in_array($menus->id, $this->menus->pluck('id')->toArray());

    }

    private function test()
    {
        $rols = Auth::user()->getroles->first();
        $this->menus = $rols->id != 2 ? $rols->getPermissions : Auth::user()->getPermissions;

    }
}
